//
//  PHCollectionController.swift
//  lookLikeIweekly
//
//  Created by Mainzxq on 16/6/7.
//  Copyright © 2016年 Mainzxq. All rights reserved.
//

import UIKit
import Photos

class PHCollectionController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PHPhotoLibraryChangeObserver {

    let flowLayout = UICollectionViewFlowLayout()
    var assetResult: PHFetchResult!
    var assetArray: [PHAsset] = [PHAsset]()
    var resultArray: [PHAsset] = [PHAsset]()
    var imageArray: [UIImage] = [UIImage]()
    
    var pickAreaRect: CGRect = CGRectMake(0, UIScreen.mainScreen().bounds.height/6, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.height/3*2)
    var topAreaRect: CGRect =  CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.height/6)
    var bottomAreaRect: CGRect = CGRectMake(0, UIScreen.mainScreen().bounds.height/6*5, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.height/6)
    var maxSelectCount: Int = 4
    
    var cachingManage: PHCachingImageManager = PHCachingImageManager()
    let cancelBtn = UIButton()
    let addToBtn = UIButton()
    
    typealias myClosure = (selectImageArray:Array<UIImage>, selectAssetArray: Array<PHAsset>) -> Void
    var closureForCallBack: myClosure?
    func myCallBack(callback: myClosure) {
        closureForCallBack = callback
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let shape: CGFloat = 3
        let cellWidth: CGFloat = (UIScreen.mainScreen().bounds.width - (CGFloat(4) + 1) * shape) / CGFloat(4)
        
        
        flowLayout.sectionInset = UIEdgeInsetsMake(0, shape, 0, shape)
        flowLayout.itemSize = CGSizeMake(cellWidth, cellWidth)
        flowLayout.minimumLineSpacing = shape
        flowLayout.minimumInteritemSpacing = shape
        
        addToBtn.frame.size = CGSize(width: 120, height: 40)
        addToBtn.center.x = self.view.center.x
        addToBtn.frame.origin.y = self.view.frame.size.height-80
        addToBtn.backgroundColor = UIColor.orangeColor()
        addToBtn.setTitle("选择完毕", forState: .Normal)
        addToBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        addToBtn.setTitleColor(UIColor.blackColor(), forState: .Highlighted)
        addToBtn.layer.cornerRadius = 5
        addToBtn.addTarget(self, action: #selector(self.sendCallBack(_:)), forControlEvents: .TouchUpInside)
        self.view.addSubview(addToBtn)
        
        cancelBtn.frame = CGRect(x: 4, y: 20, width: 60, height: 40)
        cancelBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        cancelBtn.setTitle("返 回", forState: .Normal)
        cancelBtn.addTarget(self, action: #selector(self.cancelBtnTapped), forControlEvents: .TouchUpInside)
        self.view.addSubview(cancelBtn)
        
        collectionView?.frame = pickAreaRect
        collectionView?.collectionViewLayout = flowLayout
        collectionView!.backgroundColor = UIColor.whiteColor()
        self.view.backgroundColor = UIColor.whiteColor()
        collectionView!.dataSource = self
        collectionView!.delegate = self
        collectionView!.registerClass(PhotoViewCell.self, forCellWithReuseIdentifier: "myCell")
        // view.addSubview(myCollectionView
        // 妈蛋，逼良为娼了，居然是这个东西一直导致报错，自带的collectionView
        // self.collectionView = myCollectionView
        self.collectionView?.reloadData()

        
        assetResult = getPHAssetResult()
        assetArray = getAssetArray(assetResult)
        //imageArray = getImageArray(assetArray)
    }


    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return assetArray.count
    }
    

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell:PhotoViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! PhotoViewCell
        cachingManage.requestImageForAsset(assetArray[indexPath.row] , targetSize: CGSizeZero, contentMode: .AspectFit, options: nil) { (result: UIImage?, dictionry: Dictionary?) in
            cell.imageView.image = result
            // 这里重绘单元格时，需要返回一个true和false来标识单元格状态，解决重用cell带来的重复显示的问题
            cell.isChoose = self.resultArray.contains(self.assetArray[indexPath.row])
            //self.imageArray.append(result!)
        }
        return cell
    }


    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let thisCell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoViewCell
        if resultArray.count == maxSelectCount && !thisCell.isChoose {
            print("已达到选择图片的上限")
        } else {
            thisCell.isChoose = !thisCell.isChoose
            if thisCell.isChoose {
                resultArray.append(assetArray[indexPath.row])
            } else {
                resultArray.removeAtIndex(resultArray.indexOf(assetArray[indexPath.row])!)
            }
        }
        
    }
    
    
    func photoLibraryDidChange(changeInstance: PHChange) {
        
    }
    
    
    func cancelBtnTapped() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    func sendCallBack(sender: UIButton) {
        self.imageArray = getImageArray(resultArray)
        if self.resultArray.count > 0 {
            if (self.closureForCallBack != nil && self.resultArray.count == self.imageArray.count) {
                    self.closureForCallBack!(selectImageArray:self.imageArray,selectAssetArray:self.resultArray)
            }
        }
        self.dismissViewControllerAnimated(true, completion: nil)

        
    }
    
}
